﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Markup;
using System.Globalization;
using XamlCast.Player.Model;

namespace XamlCast.Player {
    public partial class MainPage : UserControl {
        public MainPage() {
            this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.Name);
            InitializeComponent();
            CheckForNewVersion();
            GoToState(true);
        }

        private void GoToState(bool useTransitions) {
            if (Application.Current.IsRunningOutOfBrowser) {
                VisualStateManager.GoToState(this, "OutOfBrowser", useTransitions);
            } else {
                VisualStateManager.GoToState(this, "InsideBrowser", useTransitions);
            }
        }

        private void CheckForNewVersion() {
            if (Application.Current.IsRunningOutOfBrowser) {
                App.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
                Application.Current.CheckAndDownloadUpdateAsync();
            } else {
            }
        }

        void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e) {
            if (e.UpdateAvailable) {
                VisualStateManager.GoToState(this, "NewVersionAvailable", true);
            }
        }

        // If an error occurs during navigation, show an error window
        private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) {
            e.Handled = true;
            ChildWindow errorWin = new ErrorWindow(e.Uri);
            errorWin.Show();
        }

        private void btnGoBack_Click(object sender, RoutedEventArgs e) {
            if (ContentFrame.CanGoBack)
                ContentFrame.GoBack();            
        }

        private void bntGoForward_Click(object sender, RoutedEventArgs e) {
            if (ContentFrame.CanGoForward) 
                ContentFrame.GoForward();
        }

        private void FeedList_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            var pi = FeedList.SelectedItem as PodcastItem;
            if (pi != null) {
                ContentFrame.Navigate(new Uri(pi.Slug, UriKind.Relative));
            }
        }

    }
}